package com.wantup.demo01;

import java.util.concurrent.CountDownLatch;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/6/25 14:00
 * <p>
 * 闭锁：
 * 当有其他操作线程全部完成时，当前的运算才继续执行。
 */


public class TestCountDownLath {
    public static void main(String[] args) {
        CountDownLatch downLatch = new CountDownLatch(5);

        long start = System.currentTimeMillis();

        for (int i = 0; i < 5; i++) {
            new Thread(new LatchDemo(downLatch)).start();
        }
        try {
            downLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();

        System.out.println("共耗时  " + (end - start));
    }

}


class LatchDemo implements Runnable {

    private CountDownLatch countDownLatch;

    public LatchDemo() {
    }

    public LatchDemo(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {

        try {
            for (int i = 0; i < 50000; i++) {
                if (i % 2 == 0) {
                    System.out.println("偶数   " + i);
                }
            }
        } finally {

            countDownLatch.countDown();
        }

    }
}
